<template>
  <el-dialog
    :model-value="visible"
    :title="getDialogTitle()"
    width="600px"
    :close-on-click-modal="false"
    @update:model-value="$emit('update:visible', $event)"
  >
    <div class="batch-action-content">
      <!-- 选中工单信息 -->
      <el-alert
        :title="`已选择 ${tickets.length} 个工单`"
        type="info"
        show-icon
        :closable="false"
        style="margin-bottom: 20px;"
      />

      <!-- 工单列表预览 -->
      <el-card class="tickets-preview" shadow="never">
        <template #header>
          <h4>选中工单</h4>
        </template>
        <div class="tickets-list">
          <div
            v-for="ticket in tickets.slice(0, 5)"
            :key="ticket.id"
            class="ticket-item"
          >
            <div class="ticket-info">
              <span class="ticket-id">#{{ ticket.id }}</span>
              <span class="ticket-title">{{ ticket.title }}</span>
            </div>
            <div class="ticket-meta">
              <el-tag :type="getStatusType(ticket.status)" size="small">
                {{ translateStatus(ticket.status) }}
              </el-tag>
              <el-tag :type="getPriorityType(ticket.priority)" size="small">
                {{ translatePriority(ticket.priority) }}
              </el-tag>
            </div>
          </div>
          <div v-if="tickets.length > 5" class="more-tickets">
            还有 {{ tickets.length - 5 }} 个工单...
          </div>
        </div>
      </el-card>

      <!-- 批量分配表单 -->
      <el-form
        v-if="action === 'assign'"
        ref="assignFormRef"
        :model="assignForm"
        :rules="assignRules"
        label-width="100px"
      >
        <el-form-item label="分配给" prop="assigneeId">
          <el-select
            v-model="assignForm.assigneeId"
            placeholder="请选择负责人"
            style="width: 100%"
            filterable
          >
            <el-option
              v-for="agent in agents"
              :key="agent.id"
              :label="agent.name"
              :value="agent.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="分配原因" prop="reason">
          <el-input
            v-model="assignForm.reason"
            type="textarea"
            :rows="3"
            placeholder="请说明批量分配原因"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="通知方式" prop="notifyMethods">
          <el-checkbox-group v-model="assignForm.notifyMethods">
            <el-checkbox value="email">邮件通知</el-checkbox>
            <el-checkbox value="sms">短信通知</el-checkbox>
            <el-checkbox value="system">系统通知</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>

      <!-- 批量更新状态表单 -->
      <el-form
        v-if="action === 'updateStatus'"
        ref="statusFormRef"
        :model="statusForm"
        :rules="statusRules"
        label-width="100px"
      >
        <el-form-item label="新状态" prop="status">
          <el-select v-model="statusForm.status" placeholder="请选择新状态" style="width: 100%">
            <el-option label="待处理" value="OPEN" />
            <el-option label="处理中" value="IN_PROGRESS" />
            <el-option label="挂起" value="PENDING" />
            <el-option label="已解决" value="RESOLVED" />
            <el-option label="已关闭" value="CLOSED" />
          </el-select>
        </el-form-item>

        <el-form-item label="更新原因" prop="reason">
          <el-input
            v-model="statusForm.reason"
            type="textarea"
            :rows="3"
            placeholder="请说明批量更新状态的原因"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="添加备注" prop="note">
          <el-input
            v-model="statusForm.note"
            type="textarea"
            :rows="2"
            placeholder="添加备注（可选）"
            maxlength="100"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="通知相关人员" prop="notify">
          <el-switch
            v-model="statusForm.notify"
            active-text="通知"
            inactive-text="不通知"
          />
        </el-form-item>
      </el-form>

      <!-- 批量删除确认 -->
      <div v-if="action === 'delete'" class="delete-confirmation">
        <el-alert
          title="警告：此操作不可撤销！"
          type="warning"
          show-icon
          :closable="false"
        >
          <template #default>
            <div class="delete-warning">
              <p>您即将删除 {{ tickets.length }} 个工单，此操作将：</p>
              <ul>
                <li>永久删除工单及其所有相关数据</li>
                <li>删除所有评论和附件</li>
                <li>删除操作历史记录</li>
              </ul>
              <p>请确认您真的要执行此操作。</p>
            </div>
          </template>
        </el-alert>

        <el-form
          ref="deleteFormRef"
          :model="deleteForm"
          :rules="deleteRules"
          label-width="100px"
          style="margin-top: 20px;"
        >
          <el-form-item label="删除原因" prop="reason">
            <el-input
              v-model="deleteForm.reason"
              type="textarea"
              :rows="3"
              placeholder="请说明批量删除的原因"
              maxlength="200"
              show-word-limit
            />
          </el-form-item>

          <el-form-item label="确认删除" prop="confirm">
            <el-checkbox v-model="deleteForm.confirm">
              我已确认要删除这些工单，并了解此操作不可撤销
            </el-checkbox>
          </el-form-item>
        </el-form>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" :loading="submitting" @click="handleSubmit">
          {{ submitting ? '处理中...' : getSubmitButtonText() }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import { ref, reactive, computed } from 'vue'
import { useTicketsStore } from '../store/tickets'
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  name: 'BatchActionDialog',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    action: {
      type: String,
      default: '',
      validator: (value) => ['assign', 'updateStatus', 'delete'].includes(value)
    },
    tickets: {
      type: Array,
      default: () => []
    },
    agents: {
      type: Array,
      default: () => []
    }
  },
  emits: ['update:visible', 'success'],
  setup(props, { emit }) {
    const ticketsStore = useTicketsStore()
    const assignFormRef = ref()
    const statusFormRef = ref()
    const deleteFormRef = ref()
    const submitting = ref(false)

    // 批量分配表单
    const assignForm = reactive({
      assigneeId: '',
      reason: '',
      notifyMethods: ['system']
    })

    const assignRules = {
      assigneeId: [
        { required: true, message: '请选择负责人', trigger: 'change' }
      ]
    }

    // 批量更新状态表单
    const statusForm = reactive({
      status: '',
      reason: '',
      note: '',
      notify: true
    })

    const statusRules = {
      status: [
        { required: true, message: '请选择新状态', trigger: 'change' }
      ]
    }

    // 批量删除表单
    const deleteForm = reactive({
      reason: '',
      confirm: false
    })

    const deleteRules = {
      reason: [
        { required: true, message: '请说明删除原因', trigger: 'blur' }
      ],
      confirm: [
        { required: true, message: '请确认删除操作', trigger: 'change' }
      ]
    }

    // 获取对话框标题
    const getDialogTitle = () => {
      const titles = {
        assign: '批量分配工单',
        updateStatus: '批量更新状态',
        delete: '批量删除工单'
      }
      return titles[props.action] || '批量操作'
    }

    // 获取提交按钮文本
    const getSubmitButtonText = () => {
      const texts = {
        assign: '确认分配',
        updateStatus: '确认更新',
        delete: '确认删除'
      }
      return texts[props.action] || '确认'
    }

    // 提交表单
    const handleSubmit = async () => {
      try {
        let formRef = null
        let formData = null

        switch (props.action) {
          case 'assign':
            formRef = assignFormRef.value
            formData = assignForm
            break
          case 'updateStatus':
            formRef = statusFormRef.value
            formData = statusForm
            break
          case 'delete':
            formRef = deleteFormRef.value
            formData = deleteForm
            break
        }

        if (formRef) {
          await formRef.validate()
        }

        submitting.value = true

        // 执行批量操作
        await executeBatchAction(formData)

        ElMessage.success(`${getDialogTitle()}成功！`)
        emit('success')
        emit('update:visible', false)
      } catch (error) {
        console.error('批量操作失败:', error)
        ElMessage.error('操作失败：' + (error.message || '未知错误'))
      } finally {
        submitting.value = false
      }
    }

    // 执行批量操作
    const executeBatchAction = async (formData) => {
      const ticketIds = props.tickets.map(ticket => ticket.id)

      switch (props.action) {
        case 'assign':
          await batchAssign(ticketIds, formData)
          break
        case 'updateStatus':
          await batchUpdateStatus(ticketIds, formData)
          break
        case 'delete':
          await batchDelete(ticketIds, formData)
          break
      }
    }

    // 批量分配
    const batchAssign = async (ticketIds, formData) => {
      for (const ticketId of ticketIds) {
        await ticketsStore.assignTicket(ticketId, {
          assigneeId: formData.assigneeId,
          reason: formData.reason,
          notifyMethods: formData.notifyMethods
        })
      }
    }

    // 批量更新状态
    const batchUpdateStatus = async (ticketIds, formData) => {
      for (const ticketId of ticketIds) {
        await ticketsStore.updateTicket(ticketId, {
          status: formData.status,
          note: formData.note
        })
      }
    }

    // 批量删除
    const batchDelete = async (ticketIds, formData) => {
      for (const ticketId of ticketIds) {
        await ticketsStore.deleteTicket(ticketId)
      }
    }

    // 取消操作
    const handleCancel = () => {
      emit('update:visible', false)
    }

    // 工具方法
    const getStatusType = (status) => {
      const types = {
        OPEN: 'warning',
        IN_PROGRESS: 'primary',
        PENDING: 'info',
        RESOLVED: 'success',
        CLOSED: 'info'
      }
      return types[status] || 'info'
    }

    const getPriorityType = (priority) => {
      const types = {
        HIGH: 'danger',
        MEDIUM: 'warning',
        LOW: 'info'
      }
      return types[priority] || 'info'
    }

    const translateStatus = (status) => {
      const statusMap = {
        OPEN: '待处理',
        IN_PROGRESS: '处理中',
        PENDING: '挂起',
        RESOLVED: '已解决',
        CLOSED: '已关闭'
      }
      return statusMap[status] || status
    }

    const translatePriority = (priority) => {
      const priorityMap = {
        HIGH: '高',
        MEDIUM: '中',
        LOW: '低'
      }
      return priorityMap[priority] || priority
    }

    return {
      assignFormRef,
      statusFormRef,
      deleteFormRef,
      submitting,
      assignForm,
      assignRules,
      statusForm,
      statusRules,
      deleteForm,
      deleteRules,
      getDialogTitle,
      getSubmitButtonText,
      handleSubmit,
      handleCancel,
      getStatusType,
      getPriorityType,
      translateStatus,
      translatePriority
    }
  }
}
</script>

<style scoped>
.batch-action-content {
  max-height: 70vh;
  overflow-y: auto;
}

.tickets-preview {
  margin-bottom: 20px;
}

.tickets-preview h4 {
  margin: 0;
  color: #303133;
}

.tickets-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.ticket-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 12px;
  background: #f8f9fa;
  border-radius: 6px;
  border: 1px solid #e9ecef;
}

.ticket-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.ticket-id {
  font-weight: 500;
  color: #409eff;
}

.ticket-title {
  color: #303133;
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.ticket-meta {
  display: flex;
  gap: 8px;
}

.more-tickets {
  text-align: center;
  color: #909399;
  font-size: 12px;
  padding: 8px;
}

.delete-confirmation {
  margin-top: 20px;
}

.delete-warning {
  margin-top: 12px;
}

.delete-warning p {
  margin: 8px 0;
  color: #606266;
}

.delete-warning ul {
  margin: 8px 0;
  padding-left: 20px;
  color: #606266;
}

.delete-warning li {
  margin: 4px 0;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .el-dialog {
    width: 95% !important;
    margin: 0 auto;
  }
  
  .ticket-item {
    flex-direction: column;
    gap: 8px;
    align-items: flex-start;
  }
  
  .ticket-meta {
    align-self: stretch;
    justify-content: flex-start;
  }
  
  .dialog-footer {
    flex-direction: column;
  }
}
</style>
